<template>
  <a-card title="借款配置" class="card">
    <a-form layout="vertical" :form="form">
      <a-row>
        <a-col :span="10">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="初始额度"
          >
            <a-input
              prefix="$"
              type="number"
              v-decorator="[
                'max_amount',
                {
                  initialValue: product.max_amount,
                  rules: [
                    { required: true, message: '必填' }
                  ]
                },
              ]"
              :disabled="hasFormEdit"
              placeholder="必填"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" :offset="2">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="手续费"
          >
            <a-radio-group
              v-decorator="[
                'way',
                {
                  initialValue: product.s_charges.way,
                  rules: [
                    { required: true, message: '必填' }
                  ]
                },
              ]"
              :disabled="hasFormEdit"
            >
              <div class="a-form-item-radio" style="display: flex;">
                <a-form-item style="margin-bottom: 0;">
                  <a-radio value="0">
                    按固定额度
                    <a-input
                      prefix="$"
                      type="number"
                      style="width: 120px;margin-left: 5px;"
                      placeholder="按固定额度"
                      v-decorator.trim="[
                        '0',
                        {
                          initialValue: sCharges.fixed_quota,
                          rules: [
                            { validator: sCharge0Rule }
                          ],
                        },
                      ]"
                      :disabled="hasFormEdit"
                    />
                  </a-radio>
                </a-form-item>
                <a-form-item style="margin-bottom: 0;">
                  <!-- { validator: sCharge0Rule } -->
                  <a-radio value="1">
                    按借款比例
                    <a-input
                      prefix="%"
                      type="number"
                      style="width: 120px;margin-left: 5px;"
                      placeholder="按借款比例"
                      v-decorator="[
                        '1',
                        {
                          initialValue: sCharges.ratio,
                          rules: [
                            { validator: sCharge1Rule }
                          ],
                        },
                      ]"
                      :disabled="hasFormEdit"
                    />
                  </a-radio>
                </a-form-item>
              </div>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="24">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="还款方式"
          >
            <Table :disabled="hasFormEdit" v-model="product.s_repayment_way" class="table-container" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="10">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="利息比例"
          >
            <a-input
              prefix="%"
              type="number"
              v-decorator="[
                'interest_ratio',
                {
                  initialValue: product.interest_ratio,
                  rules: [{ required: true, message: '必填' }]
                },
              ]"
              placeholder="必填"
              :disabled="hasFormEdit"
            />
          </a-form-item>
        </a-col>
        <a-col :span="10" :offset="2">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="滞纳金比例"
          >
            <a-input
              prefix="%"
              type="number"
              v-decorator="[
                'late_fee_ratio',
                {
                  initialValue: product.late_fee_ratio,
                  rules: [
                    { required: true, message: '必填' }
                  ]
                },
              ]"
              placeholder="必填"
              :disabled="hasFormEdit"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="formTailLayout.wrapperCol">
        <a-button type="primary" @click.prevent="handleSubmit" :loading="loading" v-if="isEdit">
          提 交
        </a-button>
        <RoleButton v-else @click="isEdit = true" role="modify_load_settings" type="default">
          编辑
        </RoleButton>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import Table from './Table.vue'
import props from '../props'
import { modifyProduct } from '@/api/risk/admin'

const formItemLayout = {
  labelCol: { span: 23 },
  wrapperCol: { span: 23 },
}
const formTailLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 },
}
export default {
  data () {
    return {
      formItemLayout,
      formTailLayout,
      loading: false,
      form: this.$form.createForm(this),

      // 编辑
      isEdit: false,
    }
  },

  computed: {
    // 手续费
    sCharges () {
      const { way, select } = this.product.s_charges

      const fixed_quota = way === '0' ? select[way] : ''
      const ratio = way === '1' ? (select[way]) : ''

      return {
        fixed_quota,
        ratio,
      }
    },

    hasFormEdit () {
      return !this.isEdit
    },
  },

  mixins: [props],

  components: {
    Table,
  },

  methods: {
    // 固定金额
    sCharge0Rule (rule, value, callback) {
      const way = this.form.getFieldValue('way')
      if (way === '0') {
        const hasValue = value === null || value === undefined
        if (hasValue) {
          callback('必填')
          return false
        }
      }

      callback()
    },

    // 比例
    sCharge1Rule (rule, value, callback) {
      const way = this.form.getFieldValue('way')
      if (way === '1') {
        const hasValue = value === null || value === undefined
        if (hasValue) {
          callback('必填')
          return false
        }
      }

      callback()
    },

    handleSubmit () {
      this.loading = true

      this.validateFieldsForm()
        .then(() => {
          this.submitForm()
            .then((res) => {
              this.$notification.success({
                message: '修改成功!',
              })

              this.isEdit = false

              this.$emit('updated')
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 提交表单
    submitForm () {
      // 还款列表
      const { s_repayment_way } = this.product
      const new_s_repayment_way = s_repayment_way
        .filter(({ ratio, day }) => ratio && day)

      const validateFieldsKey = ['max_amount', 'interest_ratio', 'late_fee_ratio', 'way', '0', '1']

      return new Promise((resolve, reject) => {
        const fields = this.form.getFieldsValue(validateFieldsKey)
        const { max_amount, interest_ratio, way, late_fee_ratio } = fields
        // 0 机
        // 1 人
        const data = {
          max_amount,
          interest_ratio: (interest_ratio / 100).toString(),
          late_fee_ratio: (late_fee_ratio / 100).toString(),
          s_repayment_way: new_s_repayment_way.map(({ order, day, ratio }) => {
            return {
              order: order.toString(),
              day: day.toString(),
              ratio: (ratio / 100).toString(),
            }
          }),
          s_charges: {
            way,
            select: {
              '0': fields['0'],
              '1': (fields['1'] / 100).toString(),
            },
          },
        }

        modifyProduct(data)
          .then((data) => {
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

     // form validateFields
    validateFieldsForm () {
      return new Promise((resolve, reject) => {
        const {
          form: { validateFieldsAndScroll },
        } = this

        validateFieldsAndScroll((err, values) => {
          if (!err) {
            resolve()
            return false
          }
          reject(false)
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.table-container {
  margin-top: $margin-xs;
}
</style>

<style lang="scss">

.a-form-item-radio {
  .ant-form-item-children {
    line-height: 0;
    position: relative;
    top: -10px;
  }
}
</style>
